<?php

namespace App\Model;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

use App\Providers\IPServiceProvider;

class CarVinLog extends Model
{

    /**
     * 关联到模型的数据表
     *
     * @var string
     */
    protected $table = 'car_vin_log';

//    public static function insertData( $data ){
//
//
//        $now = date('Y-m-d H:i:s');
//        $sql = "insert into car_vin
//                set vin=?,info=?,source=?,created_at='$now',updated_at='$now' ";
//        $res = DB::insert($sql,
//            [ $data['vin'], $data['info'], $data['source'] ]);
//        return $res ;
//
//    }

    /**
     * 记录访问者ip地址信息
     * @param $vin
     * @return bool
     */
    public static function record( $vin ){

        $vinLog = new CarVinLog();
        $vinLog->vin = $vin;
        $ip = IPServiceProvider::getIP();
        $existed = self::where('ip', $ip)->first();
        if( !empty( $existed ) && !empty( $existed->city) ){
            $address = $existed->toarray();
        }else{
            $address = IPServiceProvider::getAddressByIPFromTaobao( $ip );
        }

        if( !empty( $address ) ){
            $vinLog->ip = $address['ip'];
            $vinLog->country = $address['country'];
            $vinLog->province = $address['province'];
            $vinLog->city = $address['city'];
            $vinLog->isp = !empty( $address['isp'] ) ? $address['isp'] : '';
            return $vinLog->save();
        }

    }


}